package com.matrix.framework.core.upload;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 文件上传工具类
 *
 * Copyright © 海平面工作室 版权所有
 *
 * @Author: Leo
 * @Create: 2025-08-17 10:00:00
 * @Since 1.2
 */
public class FileUploadUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);
    
    /**
     * 根据文件内容和名称生成唯一标识符
     * 
     * @param inputStream 文件内容输入流
     * @param filename 原始文件名
     * @return 唯一标识符字符串
     */
    public static String generateFileIdentifier(InputStream inputStream, String filename) {
        try {
            // Generate MD5 hash from file content
            String contentMd5 = DigestUtils.md5DigestAsHex(inputStream);
            // Combine with filename to make it more unique
            return DigestUtils.md5DigestAsHex((contentMd5 + filename).getBytes());
        } catch (IOException e) {
            logger.error("Error generating file identifier", e);
            // Fallback to UUID if MD5 generation fails
            return UUID.randomUUID().toString().replace("-", "");
        }
    }
    
    /**
     * 如果目录不存在则创建
     * 
     * @param directoryPath 要创建的路径
     * @return 如果目录存在或创建成功则返回true，否则返回false
     */
    public static boolean createDirectoryIfNotExists(String directoryPath) {
        Path path = Paths.get(directoryPath);
        if (!Files.exists(path)) {
            try {
                Files.createDirectories(path);
                return true;
            } catch (IOException e) {
                logger.error("Failed to create directory: " + directoryPath, e);
                return false;
            }
        }
        return true;
    }
    
    /**
     * 从文件名获取文件扩展名
     * 
     * @param filename 文件名
     * @return 文件扩展名（不含点）或无扩展名时返回空字符串
     */
    public static String getFileExtension(String filename) {
        if (filename == null || filename.isEmpty() || !filename.contains(".")) {
            return "";
        }
        return filename.substring(filename.lastIndexOf(".") + 1);
    }
    
    /**
     * 验证文件是否具有允许的扩展名
     * 
     * @param filename 要检查的文件名
     * @param allowedExtensions 允许的扩展名数组（不含点）
     * @return 如果文件具有允许的扩展名则返回true，否则返回false
     */
    public static boolean hasAllowedExtension(String filename, String[] allowedExtensions) {
        if (allowedExtensions == null || allowedExtensions.length == 0) {
            return true; // No restrictions
        }
        
        String extension = getFileExtension(filename).toLowerCase();
        if (extension.isEmpty()) {
            return false;
        }
        
        for (String allowedExt : allowedExtensions) {
            if (extension.equals(allowedExt.toLowerCase())) {
                return true;
            }
        }
        
        return false;
    }
}